<template>
  <div class="user-dialog-select">
    <!-- 触发选择器 -->
    <div class="user-select-wrapper" @click="openDialog" :class="{ disabled: disabled }">
      <div class="select-input">
        <!-- 选择框前缀图标 -->
        <el-icon class="prefix-icon"><User /></el-icon>

        <!-- 已选用户标签展示 -->
        <div class="selected-content">
          <div v-if="selectedUsers.length === 0" class="placeholder-text">
            {{ placeholder }}
          </div>
          <div v-else class="selected-tags">
            <el-tag
              v-for="user in selectedUsers"
              :key="user._id"
              closable
              @close.stop="removeUser(user._id)"
              class="user-tag"
              size="small"
            >
              <span class="tag-text">{{ user.userName }}</span>
            </el-tag>
          </div>
        </div>

        <!-- 下拉箭头 -->
        <el-icon class="suffix-icon"><ArrowDown /></el-icon>
      </div>
    </div>

    <!-- 用户选择弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :width="dialogWidth"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      append-to-body
      class="user-select-dialog"
    >
      <div class="dialog-content">
        <!-- 左侧组织树 -->
        <div class="org-tree-panel">
          <div class="panel-header">
            <h4>组织架构</h4>
            <div class="header-actions">
              <el-button size="small" text @click="clearOrgFilter" title="显示所有用户">
                <el-icon><User /></el-icon>
                全部
              </el-button>
            </div>
          </div>
          <div class="tree-container">
            <el-tree
              ref="orgTreeRef"
              :data="orgTreeData"
              :props="treeProps"
              node-key="_id"
              :expand-on-click-node="false"
              :check-on-click-node="false"
              class="org-tree"
            >
              <template #default="{ data }">
                <div
                  :class="['tree-node', { active: currentOrgFilter === data._id }]"
                  @click="selectOrgUsers(data)"
                  :title="`点击筛选 ${data.name} 部门下的用户`"
                >
                  <el-icon class="node-icon">
                    <OfficeBuilding v-if="!data.pid" />
                    <Files v-else />
                  </el-icon>
                  <span class="node-label">{{ data.name }}</span>
                  <span class="user-count">({{ data.userCount || 0 }})</span>
                  <el-icon v-if="currentOrgFilter === data._id" class="filter-icon">
                    <Check />
                  </el-icon>
                </div>
              </template>
            </el-tree>
          </div>
        </div>

        <!-- 右侧用户列表 -->
        <div class="user-list-panel">
          <div class="panel-header">
            <h4>用户列表 ({{ filteredUserList.length }})</h4>
            <div class="header-actions">
              <el-input v-model="searchKeyword" placeholder="搜索用户" clearable @input="handleSearch" class="search-input">
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 用户列表 -->
          <div class="user-list-container">
            <!-- 已选用户区域 -->
            <div v-if="tempSelectedUsers.length > 0" class="selected-users-section">
              <!-- <div class="section-header">
                <h5>已选用户 ({{ tempSelectedUsers.length }}{{ maxCount > 0 ? `/${maxCount}` : "" }})</h5>
                <el-button size="small" text type="danger" @click="clearAllSelection" title="清空所有选择">
                  <el-icon><Delete /></el-icon>
                  清空
                </el-button>
              </div> -->
              <div class="selected-users-list">
                <div v-for="user in tempSelectedUsers" :key="user._id" class="selected-user-item">
                  <el-avatar :src="user.userPicId" :size="24">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <span class="user-name">{{ user.userName }}</span>
                  <span class="user-org">{{ getOrgName(user.orgId) }}</span>
                  <el-button size="small" text type="danger" @click="removeFromSelection(user._id)" title="移除用户">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 当前筛选信息 -->
            <div v-if="currentOrgName" class="filter-info">
              <el-tag type="info" closable @close="clearOrgFilter">
                {{ currentOrgName }}
              </el-tag>
              <el-button size="small" text type="primary" @click="clearOrgFilter"> 显示所有用户 </el-button>
            </div>

            <div class="user-list-wrapper">
              <div v-if="filteredUserList.length === 0" class="empty-state">
                <el-empty description="暂无用户数据" />
              </div>
              <div v-else class="user-grid">
                <div
                  v-for="user in paginatedUsers"
                  :key="user._id"
                  :class="['user-item', { selected: isUserSelected(user._id) }]"
                  @click="toggleUser(user)"
                >
                  <div class="user-info">
                    <el-avatar :src="user.userPicId" :size="32">
                      <el-icon><User /></el-icon>
                    </el-avatar>
                    <div class="user-details">
                      <div class="user-name">{{ user.userName }}</div>
                      <div class="user-org">{{ getOrgName(user.orgId) }}</div>
                    </div>
                  </div>
                  <div class="selection-indicator">
                    <el-icon v-if="isUserSelected(user._id)" class="selected-icon">
                      <Check />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>

            <!-- 固定在底部的分页 -->
            <div v-if="filteredUserList.length > pageSize" class="pagination-wrapper">
              <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :total="filteredUserList.length"
                layout="prev, pager, next, jumper"
                small
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 弹窗底部操作 -->
      <template #footer>
        <div class="dialog-footer">
          <div class="selection-summary">
            <span>已选择 {{ tempSelectedUsers.length }} 位用户</span>
            <span v-if="maxCount > 0">(最多可选 {{ maxCount }} 位)</span>
          </div>
          <div class="footer-actions">
            <el-button @click="cancelSelection">取消</el-button>
            <el-button @click="clearAllSelection" v-if="tempSelectedUsers.length > 0"> 清空选择 </el-button>
            <el-button type="primary" @click="confirmSelection"> 确定 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="UserDialogSelect">
import { ref, computed, onMounted, watch, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { User, ArrowDown, OfficeBuilding, Files, Search, Check, Close } from "@element-plus/icons-vue";
import { useDataStore } from "@/stores/modules/data";
import { Md5 } from "ts-md5";
import apiService from "@/api/services/apiService";
import { DataState } from "@/enums/sysEnum";
import { Org, Users as UserInfo } from "@/api/types/base";

// Props 定义
interface UserDialogSelectProps {
  modelValue?: string[] | UserInfo[];
  placeholder?: string;
  disabled?: boolean;
  multiple?: boolean;
  maxCount?: number;
  orgFilter?: string[];
  dialogTitle?: string;
  dialogWidth?: string;
  externalUsers?: UserInfo[];
  externalOrgs?: Org[];
}

const props = withDefaults(defineProps<UserDialogSelectProps>(), {
  modelValue: () => [],
  placeholder: "请选择用户",
  disabled: false,
  multiple: true,
  maxCount: 0,
  orgFilter: () => [],
  dialogTitle: "选择用户",
  dialogWidth: "1000px",
  externalUsers: undefined,
  externalOrgs: undefined
});

// 组织节点接口定义，继承自Org类型
interface OrgNode extends Org {
  children?: OrgNode[];
  userCount?: number;
}

// 确保初始化为空数组，避免类型推断为never[]
const selectedUsers = ref<UserInfo[]>([]);
const tempSelectedUsers = ref<UserInfo[]>([]);
const searchKeyword = ref("");
const currentOrgFilter = ref<string>("");
const currentOrgName = ref<string>("");
const orgTreeRef = ref();
const currentPage = ref(1);
const pageSize = ref(20);
const dialogVisible = ref(false);

const dataStore = useDataStore();

// 组织树数据
const orgTreeData = ref<OrgNode[]>([]);
const treeProps = {
  children: "children",
  label: "name"
};

// 创建组织ID到组织名称的映射
const orgIdToNameMap = computed(() => {
  const map = new Map<string, string>();
  const buildMap = (nodes: OrgNode[]) => {
    nodes.forEach(node => {
      map.set(node._id, node.name);
      if (node.children && node.children.length > 0) {
        buildMap(node.children);
      }
    });
  };

  if (orgTreeData.value && orgTreeData.value.length > 0) {
    buildMap(orgTreeData.value);
  }

  return map;
});

// 获取组织名称的函数
const getOrgName = (orgId: string) => {
  if (!orgId) return "未分配部门";
  return orgIdToNameMap.value.get(orgId) || orgId;
};

// 用户列表数据
const userParamKey = ref<string>("");
const allUserList = computed(() => {
  // 如果有外部传入的用户数据，优先使用
  if (props.externalUsers && props.externalUsers.length > 0) {
    // 确保返回的用户都有_id
    return props.externalUsers.filter(user => user._id);
  }

  // 确保返回的是数组类型
  if (userParamKey.value) {
    const data = dataStore.getCommonDataByName(userParamKey.value);
    return Array.isArray(data) ? (data as UserInfo[]).filter(user => user._id) : [];
  } else {
    return Array.isArray(dataStore.userList) ? (dataStore.userList as UserInfo[]).filter(user => user._id) : [];
  }
});

// 递归获取组织及其所有下级组织的ID列表
const getAllSubOrgIds = (orgId: string): string[] => {
  // 确保orgId存在
  if (!orgId) {
    return [];
  }

  const orgIds = [orgId]; // 包含当前组织

  const findSubOrgs = (nodes: OrgNode[], targetId: string): string[] => {
    const subIds: string[] = [];

    for (const node of nodes) {
      // 确保node._id存在
      if (!node._id) {
        continue;
      }

      if (node._id === targetId && node.children) {
        // 找到目标组织，获取所有下级组织
        const getChildIds = (children: OrgNode[]): string[] => {
          const ids: string[] = [];
          children.forEach(child => {
            // 确保child._id存在
            if (child._id) {
              ids.push(child._id);
              if (child.children && child.children.length > 0) {
                ids.push(...getChildIds(child.children));
              }
            }
          });
          return ids;
        };
        subIds.push(...getChildIds(node.children));
        break;
      } else if (node.children && node.children.length > 0) {
        // 递归查找
        subIds.push(...findSubOrgs(node.children, targetId));
      }
    }

    return subIds;
  };

  // 获取所有下级组织ID
  const subOrgIds = findSubOrgs(orgTreeData.value, orgId);
  orgIds.push(...subOrgIds);

  return orgIds;
};

// 过滤后的用户列表
const filteredUserList = computed(() => {
  // 确保allUserList.value是数组
  let users = Array.isArray(allUserList.value) ? allUserList.value : [];

  // 组织过滤
  if (props.orgFilter && props.orgFilter.length > 0) {
    users = users.filter(user => user.orgId && props.orgFilter.includes(user.orgId));
  }

  // 当前选择的组织过滤（包含下级组织）
  if (currentOrgFilter.value) {
    const orgIds = getAllSubOrgIds(currentOrgFilter.value);
    users = users.filter(user => user.orgId && orgIds.includes(user.orgId));
  }

  // 搜索关键词过滤
  if (searchKeyword.value && searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase();
    users = users.filter(user => user.userName && user.userName.toLowerCase().includes(keyword));
  }

  return users;
});

// 分页用户列表
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUserList.value.slice(start, end);
});

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  async newValue => {
    // 添加类型安全检查
    if (!newValue) {
      selectedUsers.value = [];
      return;
    }

    // 根据传入的值类型处理
    if (Array.isArray(newValue) && newValue.length > 0) {
      // 如果传入的是字符串数组（用户ID）
      if (typeof newValue[0] === "string") {
        // 根据用户ID获取用户详细信息
        const userIds = newValue as string[];
        const users = await getUserInfoByIds(userIds);
        selectedUsers.value = users;
      }
      // 如果传入的是用户对象数组
      else if (typeof newValue[0] === "object" && newValue[0] !== null) {
        selectedUsers.value = newValue as UserInfo[];
      }
    } else {
      selectedUsers.value = [];
    }
  },
  { immediate: true }
);

// 根据用户ID获取用户详细信息
const getUserInfoByIds = async (userIds: string[]): Promise<UserInfo[]> => {
  // 添加类型安全检查
  if (!Array.isArray(userIds) || userIds.length === 0) {
    return [];
  }

  // 如果有外部传入的用户数据，直接从中查找
  if (props.externalUsers && props.externalUsers.length > 0) {
    return props.externalUsers.filter(user => user._id && userIds.includes(user._id));
  }

  try {
    const response = await apiService.find("users", { _id: { $in: userIds } });
    // 添加类型安全检查
    if (response && response.data && Array.isArray(response.data)) {
      // 过滤掉没有_id的用户
      return response.data.filter(user => user._id);
    } else {
      return [];
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    // 如果获取失败，返回简单的用户对象，但确保有_id
    return userIds
      .filter(id => id)
      .map(id => ({
        _id: id,
        userName: id,
        loginName: "",
        nickName: "",
        userPicId: "",
        password: "",
        mobile: "",
        email: "",
        sex: "",
        post: "",
        workNo: "",
        orgId: "",
        sort: 0,
        state: "",
        roleIds: []
      }));
  }
};

// 生命周期
onMounted(async () => {
  // 只在第一次打开弹窗时加载数据，避免重复请求
  console.log("用户选择组件初始化完成");
});

onBeforeUnmount(() => {
  // 组件销毁前清理
  clearCache();
});

// 清理缓存数据
const clearCache = () => {
  userParamKey.value = "";
  orgTreeData.value = [];
};

// 加载用户列表
const loadUserList = async () => {
  // 如果有外部传入的用户数据，不需要加载
  if (props.externalUsers && props.externalUsers.length > 0) {
    return;
  }

  try {
    // 设置超时处理
    const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("加载用户列表超时")), 10000));

    if (props.orgFilter && props.orgFilter.length > 0) {
      // 如果有组织过滤条件，使用特定查询
      const condition = {
        orgId: { $in: props.orgFilter },
        state: DataState.DEFAULT
      };
      userParamKey.value = Md5.hashStr(JSON.stringify(condition));
      // 使用Promise.race实现超时控制
      await Promise.race([dataStore.findList(userParamKey.value, () => apiService.find("users", condition)), timeoutPromise]);
    } else {
      // 否则加载所有用户
      await Promise.race([dataStore.findUserList(), timeoutPromise]);
    }

    // 确保加载的用户数据都有_id
    if (userParamKey.value) {
      const data = dataStore.getCommonDataByName(userParamKey.value);
      if (Array.isArray(data)) {
        dataStore.commonData.set(
          userParamKey.value,
          data.filter(user => user._id)
        );
      }
    } else {
      if (Array.isArray(dataStore.userList)) {
        dataStore.userList = dataStore.userList.filter(user => user._id);
      }
    }
  } catch (error: any) {
    console.error("加载用户列表失败:", error);
    ElMessage.error(error.message === "加载用户列表超时" ? "加载用户列表超时，请稍后重试" : "加载用户列表失败");
  }
};

// 加载组织树
const loadOrgTree = async () => {
  // 如果有外部传入的组织数据，直接使用
  if (props.externalOrgs && props.externalOrgs.length > 0) {
    // 确保组织节点都有_id和name
    const validOrgs = props.externalOrgs.filter(org => org._id && org.name);
    orgTreeData.value = validOrgs.map(org => ({
      ...org,
      children: [],
      userCount: 0
    })) as OrgNode[];
    await updateUserCount();
    return;
  }

  try {
    // 设置超时处理
    const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("加载组织树超时")), 10000));

    const response = (await Promise.race([apiService.find<Org[]>("orgs", {}), timeoutPromise])) as any;

    const orgList = response.data || [];

    // 构建组织树并统计用户数量
    orgTreeData.value = buildOrgTree(orgList);
    await updateUserCount();
  } catch (error: any) {
    console.error("加载组织树失败:", error);
    ElMessage.error(error.message === "加载组织树超时" ? "加载组织树超时，请稍后重试" : "加载组织树失败");
  }
};

// 更新组织用户数量统计（包含下级组织）
const updateUserCount = async () => {
  // 添加类型安全检查
  if (!Array.isArray(orgTreeData.value) || orgTreeData.value.length === 0) {
    return;
  }

  const updateCount = (org: OrgNode) => {
    // 确保org._id存在
    if (!org._id) {
      return;
    }

    // 获取该组织及所有下级组织的用户数量
    const orgIds = getAllSubOrgIds(org._id);
    const usersInOrgAndSubs = allUserList.value.filter(user => user.orgId && orgIds.includes(user.orgId));
    org.userCount = usersInOrgAndSubs.length;

    // 递归更新子组织
    if (org.children && org.children.length > 0) {
      org.children.forEach(updateCount);
    }
  };

  orgTreeData.value.forEach(updateCount);
};

// 构建组织树结构
const buildOrgTree = (orgList: Org[]): OrgNode[] => {
  // 添加类型安全检查
  if (!Array.isArray(orgList) || orgList.length === 0) {
    console.warn("组织数据为空");
    return [];
  }

  const orgMap = new Map<string, OrgNode>();
  const rootOrgs: OrgNode[] = [];

  console.log("原始组织数据:", orgList);

  // 创建组织节点映射
  orgList.forEach(org => {
    // 添加类型安全检查
    if (org && org._id && org.name) {
      orgMap.set(org._id, {
        ...org, // 展开所有原始属性
        children: [],
        userCount: 0
      });
    }
  });

  console.log("组织映射:", orgMap);

  // 构建树结构
  orgMap.forEach(org => {
    if (org.pid && orgMap.has(org.pid)) {
      // 有父组织且父组织存在
      const parentOrg = orgMap.get(org.pid);
      if (parentOrg) {
        if (!parentOrg.children) {
          parentOrg.children = [];
        }
        parentOrg.children.push(org);
      }
    } else {
      // 没有父组织或父组织不存在，作为根节点
      rootOrgs.push(org);
    }
  });

  console.log("构建的组织树:", rootOrgs);
  return rootOrgs;
};

// 选择组织下的用户（仅过滤显示，不自动选择）
const selectOrgUsers = (orgNode: OrgNode) => {
  // 添加类型安全检查
  if (!orgNode || !orgNode._id || !orgNode.name) {
    console.warn("Invalid orgNode passed to selectOrgUsers:", orgNode);
    return;
  }

  currentOrgFilter.value = orgNode._id;
  currentOrgName.value = orgNode.name;
  currentPage.value = 1;
};

// 清除组织过滤
const clearOrgFilter = () => {
  currentOrgFilter.value = "";
  currentOrgName.value = "";
  currentPage.value = 1;
  ElMessage.info("已清除组织筛选，显示所有用户");
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 刷新用户列表
const refreshUserList = () => {
  loadUserList();
  loadOrgTree();
  ElMessage.success("已刷新用户列表和组织架构");
};

// 判断用户是否已选择
const isUserSelected = (userId: string): boolean => {
  // 确保userId存在
  if (!userId) {
    return false;
  }

  return tempSelectedUsers.value.some(user => user._id === userId);
};

// 判断是否还能选择更多用户
const canSelectMore = (): boolean => {
  if (props.maxCount === 0) return true;
  return tempSelectedUsers.value.length < props.maxCount;
};

// 切换用户选择状态
const toggleUser = (user: UserInfo) => {
  // 添加类型安全检查
  if (!user || !user._id) {
    console.warn("Invalid user passed to toggleUser:", user);
    return;
  }

  const index = tempSelectedUsers.value.findIndex(u => u._id === user._id);

  if (index > -1) {
    // 取消选择
    tempSelectedUsers.value.splice(index, 1);
  } else {
    // 选择用户
    if (canSelectMore()) {
      tempSelectedUsers.value.push(user);
    } else {
      ElMessage.warning(`最多只能选择 ${props.maxCount} 位用户`);
    }
  }
};

// 移除单个用户（从临时选择中）
const removeFromSelection = (userId: string) => {
  // 确保userId存在
  if (!userId) {
    return;
  }

  const index = tempSelectedUsers.value.findIndex(user => user._id === userId);
  if (index > -1) {
    tempSelectedUsers.value.splice(index, 1);
  }
};

// 移除单个用户（从确认选择中）
const removeUser = (userId: string) => {
  // 确保userId存在
  if (!userId) {
    return;
  }

  const index = selectedUsers.value.findIndex(user => user._id === userId);
  if (index > -1) {
    selectedUsers.value.splice(index, 1);
    updateModelValue();
  }
};

// 打开弹窗
const openDialog = async () => {
  if (props.disabled) return;

  tempSelectedUsers.value = [...selectedUsers.value];
  currentOrgFilter.value = "";
  currentOrgName.value = "";
  searchKeyword.value = "";
  currentPage.value = 1;

  dialogVisible.value = true;

  // 延迟加载数据，确保弹窗已渲染，但避免重复请求
  setTimeout(async () => {
    try {
      // 只有当数据为空时才加载
      if (allUserList.value.length === 0 && (!props.externalUsers || props.externalUsers.length === 0)) {
        await loadUserList();
      }

      // 确保orgTreeData.value是数组类型
      if (
        Array.isArray(orgTreeData.value) &&
        orgTreeData.value.length === 0 &&
        (!props.externalOrgs || props.externalOrgs.length === 0)
      ) {
        await loadOrgTree();
      }
    } catch (error) {
      console.error("加载数据失败:", error);
      ElMessage.error("加载数据失败，请稍后重试");
    }
  }, 100);
};

// 取消选择
const cancelSelection = () => {
  dialogVisible.value = false;
  tempSelectedUsers.value = [];
};

// 清空所有选择
const clearAllSelection = () => {
  tempSelectedUsers.value = [];
  ElMessage.info("已清空所有选择");
};

// 确认选择
const confirmSelection = () => {
  // 确保tempSelectedUsers.value是数组
  selectedUsers.value = Array.isArray(tempSelectedUsers.value) ? [...tempSelectedUsers.value] : [];
  updateModelValue();
  dialogVisible.value = false;

  ElMessage.success(`已选择 ${selectedUsers.value.length} 位用户`);
};

// 更新 v-model
const updateModelValue = () => {
  // 确保selectedUsers.value是数组
  const selected = Array.isArray(selectedUsers.value) ? selectedUsers.value : [];

  // 根据传入的值类型返回相应的数据格式
  if (props.modelValue && Array.isArray(props.modelValue) && props.modelValue.length > 0) {
    // 如果原始传入的是字符串数组，返回用户ID数组
    if (typeof props.modelValue[0] === "string") {
      const userIds = selected.map(user => user._id);
      emit("update:modelValue", userIds);
      emit("change", userIds);
      return;
    }
  }

  // 默认返回用户对象数组
  emit("update:modelValue", selected);
  emit("change", selected);
};

// 清空选择（对外暴露）
const clearSelection = () => {
  selectedUsers.value = [];
  updateModelValue();
};

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: string[] | UserInfo[]): void;
  (e: "change", value: string[] | UserInfo[]): void;
}>();

// 对外暴露的方法
defineExpose({
  loadUserList,
  loadOrgTree,
  clearSelection,
  refreshUserList
});
</script>

<style lang="scss" scoped>
.user-dialog-select {
  width: 100%;
}
.user-select-wrapper {
  position: relative;
  width: 100%;
  cursor: pointer;
  &.disabled {
    pointer-events: none;
    cursor: not-allowed;
    opacity: 0.6;
  }
}
.select-input {
  position: relative;
  box-sizing: border-box;
  display: flex;
  align-items: flex-start;
  min-height: 32px;
  padding: 4px 30px 4px 8px;
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  transition: all 0.3s;
  &:hover {
    border-color: var(--el-color-primary);
  }
  &:focus-within {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 2px rgb(from var(--el-color-primary) r g b / 20%);
  }
}
.prefix-icon {
  flex-shrink: 0;
  margin-top: 4px;
  margin-right: 8px;
  font-size: 14px;
  color: var(--el-text-color-placeholder);
}
.selected-content {
  display: flex;
  flex: 1;
  align-items: flex-start;
  min-width: 0;
  min-height: 22px;
}
.placeholder-text {
  font-size: 14px;
  line-height: 22px;
  color: var(--el-text-color-placeholder);
  user-select: none;
}
.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: flex-start;
  width: 100%;
}
.user-tag {
  display: inline-flex;
  gap: 4px;
  align-items: center;
  max-width: 120px;
  height: 22px;
  padding: 0 6px;
  font-size: 12px;
  line-height: 1;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  background: var(--el-color-info-light-8);
  border: 1px solid var(--el-color-info-light-6);
  border-radius: 11px;
  .tag-avatar {
    flex-shrink: 0;
    width: 14px;
    height: 14px;
  }
  .tag-text {
    flex: 1;
    overflow: hidden;
    color: var(--el-text-color-primary);
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .tag-org {
    margin-left: 4px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
  :deep(.el-tag__close) {
    margin-left: 2px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
    &:hover {
      color: var(--el-text-color-primary);
      background: var(--el-color-info-light-5);
    }
  }
}
.suffix-icon {
  position: absolute;
  top: 50%;
  right: 8px;
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  pointer-events: none;
  transition: transform 0.3s;
  transform: translateY(-50%);
}
.user-select-wrapper:hover .suffix-icon,
.user-select-wrapper:focus-within .suffix-icon {
  transform: translateY(-50%) rotate(180deg);
}
.user-select-dialog .dialog-content {
  display: flex;
  gap: 16px;
  height: 600px;
}
.org-tree-panel {
  display: flex;
  flex-direction: column;
  width: 280px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
}
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  .header-actions {
    display: flex;
    gap: 4px;
    align-items: center;
  }
}
.panel-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.tree-container {
  flex: 1;
  padding: 8px;
  overflow: auto;
}
.tree-node {
  display: flex;
  gap: 6px;
  align-items: center;
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  &:hover {
    background: var(--el-color-primary-light-9);
  }
  &.active {
    color: var(--el-color-primary);
    background: var(--el-color-primary-light-8);
    .node-label {
      font-weight: 600;
    }
  }
}
.node-icon {
  color: var(--el-color-primary);
}
.node-label {
  flex: 1;
  font-size: 13px;
}
.user-count {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.filter-icon {
  font-size: 14px;
  color: var(--el-color-success);
}
.user-list-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
}
.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}
.search-input {
  width: 200px;
}
.filter-info {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 8px 16px;
  background: var(--el-bg-color-page);
  border-bottom: 1px solid var(--el-border-color-lighter);
}
.user-list-container {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
}
.user-list-wrapper {
  flex: 1;
  overflow: auto;
}
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}
.user-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 12px;
}
.user-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  cursor: pointer;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  transition: all 0.3s;
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
  }
  &.selected {
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
    .selected-icon {
      color: var(--el-color-primary);
    }
  }
}
.user-info {
  display: flex;
  flex: 1;
  gap: 10px;
  align-items: center;
}
.user-details {
  flex: 1;
  min-width: 0;
}
.user-name {
  margin-bottom: 2px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}
.user-org {
  overflow: hidden;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.selection-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  .selected-icon {
    font-size: 16px;
    font-weight: bold;
  }
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  margin-top: 10px;
  border-top: 1px solid var(--el-border-color-lighter);
}
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.selection-summary {
  font-size: 14px;
  color: var(--el-text-color-regular);
}
.footer-actions {
  display: flex;
  gap: 12px;
}
.selected-users-section {
  padding: 12px 16px;
  background: var(--el-color-primary-light-9);
  border-bottom: 1px solid var(--el-border-color-lighter);
}
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.section-header h5 {
  margin: 0;
  font-size: 13px;
  font-weight: 600;
  color: var(--el-color-primary);
}
.selected-users-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
}
.selected-user-item {
  display: flex;
  gap: 6px;
  align-items: center;
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-light);
  border-radius: 16px;
}
.selected-user-item .user-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}
.selected-user-item .user-org {
  color: var(--el-text-color-secondary);
}

@media (width <= 1200px) {
  .user-select-dialog .dialog-content {
    height: 500px;
  }
  .org-tree-panel {
    width: 240px;
  }
  .user-list-panel .user-list-container .user-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}

@media (width <= 768px) {
  .user-select-dialog .dialog-content {
    flex-direction: column;
    height: 600px;
  }
  .org-tree-panel {
    width: 100%;
    height: 200px;
  }
  .user-list-panel .user-list-container .user-grid {
    grid-template-columns: 1fr;
  }
}
</style>
